<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Database\Eloquent\Model;

/**
 * 同步模型商品到 ES
 * @package App\Jobs
 */
class SyncModelToES implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $goods;

    public function __construct(Model $goods)
    {
        $this->goods = $goods;
    }

    /**
     * 根据模型类型获取 ES索引名称
     * @param string $class
     * @return string
     */
    protected function getEsIndex()
    {
        $refClass = new \ReflectionClass(get_class($this->goods));
        return strtolower('edu' . $refClass->getShortName());
    }

    public function handle()
    {
        $params = [
            'index' => $this->getEsIndex(),
            'id'    => $this->goods->id,
            'body'  => $this->goods->elasticsearchArray()
        ];
        app('es')->index($params);
    }
}
